package les.projeto;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class SubjectsView extends Activity{
	
	private String subjectName = "";
	private String subjectTeacher = "";
	private String subjectPlace = "";
	
	private String taskName = "";
	private String taskWeight = "";
	private String taskGrade = "";
	private String date = "";
	
	
	private int subjectCredits = 1;

	
	private String weightName = "";
	private String weightPerc = "";

	
	private String[][] aboutTasks = null;
	private String[][] aboutClasses = null;
	private String[] bdWeights = null;
//	private String[] bdLocals = null;
//	private int subjectHour = 0;
//	private int subjectMinute = 0;
	
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.subjects);
	
		Intent intent = getIntent();
		date = intent.getStringExtra("date");
		subjectName = intent.getStringExtra("subjectName");
	    subjectTeacher = intent.getStringExtra("subjectTeacher");
	    subjectPlace = intent.getStringExtra("subjectPlace");
//	    System.out.println("Creditos Aqui:" + intent.getStringExtra("credits"));
	    subjectCredits = Integer.valueOf(intent.getStringExtra("credits"));
	    TextView screen = (TextView) findViewById(R.id.subjectName);
	    screen.setText(subjectName);
	    
	    TextView teacher = (TextView) findViewById(R.id.teacherName);
	    teacher.setText(subjectTeacher);
	    TextView place = (TextView) findViewById(R.id.placeName);
	    place.setText(subjectPlace);
	    TextView credit = (TextView) findViewById(R.id.credits);
	    credit.setText(String.valueOf(subjectCredits));

	       
	    updateWeights();
	    updateListValues();
	    ListView subjects = (ListView)findViewById(R.id.listViewTasks);
	    subjects.setOnItemClickListener(new OnItemClickListener() {
	    	@Override
	    	public void onItemClick(AdapterView<?> parent, View view,
	    		int position, long id) {
	    		showTasks(aboutTasks[position][0], aboutTasks[position][1],
	    				aboutTasks[position][2]);
	    		
	    	}
	    });
	    
	    ListView classes = (ListView)findViewById(R.id.ListViewClasses);
	    classes.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
                showClasses(aboutClasses[position][0], aboutClasses[position][1],
                        aboutClasses[position][2], aboutClasses[position][3]);
                
            }
        });
	  
}	
	private void seeGrades(){
		final AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle("Grades");
//		 helpBuilder.setMessage();
		 helpBuilder.setPositiveButton("Add weight", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  addWeightName();
				  dialog.cancel();
			  }
		 });
//
		 helpBuilder.setNegativeButton("Back", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  dialog.cancel();
			  }
			 });
//		 
		 helpBuilder.setNeutralButton("Credits", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
//				  BD bd = new BD();
//				  bd.removeSubject(SingleSemesterView.this, name);
				  editCredits();
				  TextView credit = (TextView) findViewById(R.id.credits);
			      credit.setText(String.valueOf(subjectCredits));
				  dialog.cancel();
//				  startActivity(getIntent()); 
//				  finish();
			  }
		 });
//		
		 
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
	}
	private void showTasks(final String name, final String weight, 
			final String grade) {
		 final AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle(name);
//		 helpBuilder.setMessage();
		 helpBuilder.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
//				  editSubjectName(name, description, teacher, local);
				  dialog.cancel();
			  }
		 });

		 helpBuilder.setNegativeButton("Grade", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				 editTaskGrade(name);
				  dialog.cancel();
				  
			  }
			 });
		 
		 helpBuilder.setNeutralButton("remove", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  BD bd = new BD();
				  bd.removeTask(SubjectsView.this, name);
				  dialog.cancel();
				  startActivity(getIntent()); 
				  finish();
			  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
	}

	private void showClasses(final String id, final String initialTime, 
            final String endTime, final String repetitions) {
         final AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
         helpBuilder.setTitle(repetitions);
//       helpBuilder.setMessage();
         helpBuilder.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                  editClass(id, initialTime, endTime, repetitions);
//                editSubjectName(name, description, teacher, local);
                  dialog.cancel();
              }
         });

         helpBuilder.setNegativeButton("Back", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                  dialog.cancel();
                  
              }
             });
         
         helpBuilder.setNeutralButton("remove", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                BD bd = new BD();
                  bd.removeClass(SubjectsView.this, id);
                  dialog.cancel();
                  startActivity(getIntent()); 
                  finish();
              }
         });
        
         AlertDialog helpDialog = helpBuilder.create();
         helpDialog.show();
    }
	
	protected void editTaskGrade(final String name){
		AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		BD bd = new BD();
		String grade = String.valueOf(bd.getTaskGrade(this, name));
//		finish();
		 helpBuilder.setTitle("Editing activity's grade " + grade);
		 helpBuilder.setMessage("Nova nota:");
		 final EditText input = new EditText(this);
		 input.setSingleLine();
		 input.setText(grade);
		 helpBuilder.setView(input);
	
		 helpBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  taskGrade = "";
				  taskGrade = input.getText().toString();
				  dialog.cancel();
				  if (!taskGrade.trim().isEmpty()){
					  editTaskGradeinBD(name, taskGrade);
				  }
//				  editSubjectTeacher(name, teacher , local);
			  }
		 });
		 
		 helpBuilder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
		
		
	}
	protected void editCredits(){
		AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
//		BD bd = new BD();
//		String grade = String.valueOf(bd.getTaskGrade(this, name));
//		finish();
		 helpBuilder.setTitle("Editing Credits of the discipline: " + subjectName);
		 helpBuilder.setMessage("Credits:");
		 final EditText input = new EditText(this);
		 input.setSingleLine();
		 input.setText(String.valueOf(subjectCredits));
		 helpBuilder.setView(input);
	
		 helpBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
			     
				  subjectCredits = Integer.valueOf(input.getText().toString());
				  
				  dialog.cancel();
				  if (subjectCredits >= 0){
					  editCreditsInBD();
				  }
//				  editSubjectTeacher(name, teacher , local);
			  }
		 });
		 
		 helpBuilder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
		
		
	}
	protected void editTaskGradeinBD(String name,String newGrade){
		 BD bd = new BD();
		 bd.editTaskGrade(this, name, Float.valueOf(newGrade));
//		 finish();
		
	}
	protected void editCreditsInBD(){
		 BD bd = new BD();
		 bd.editSubjectCredits(this, subjectName, subjectCredits);
//		 finish();
		
	}
	protected void addTaskName() {
		 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle("Add task");
		 helpBuilder.setMessage("Enter the task name: ");
		 final EditText input = new EditText(this);
		 input.setSingleLine();
		 input.setText("");
		 helpBuilder.setView(input);
	
		 helpBuilder.setPositiveButton("Next", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  taskName = "";
				  taskName = input.getText().toString();
				  dialog.cancel();
				  addTaskWeight();
			  }
		 });
		 helpBuilder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
	}
	protected void addWeightName() {
		 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle("Ads weigth");
		 helpBuilder.setMessage("Name: ");
		 final EditText input = new EditText(this);
		 input.setSingleLine();
		 input.setText("");
		 helpBuilder.setView(input);
	
		 helpBuilder.setPositiveButton("Next", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  weightName = "";
				  weightName = input.getText().toString();
				  if(weightName.trim().isEmpty()){
					  weightName = "SemNome";
				  }
				  addWeightPerc();
				  dialog.cancel();
				  
			  }
		 });
		 helpBuilder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
	}
	
	protected void addWeightPerc() {
		 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle("Add weight");
		 helpBuilder.setMessage("wieght (0-100): ");
		 final EditText input = new EditText(this);
		 input.setSingleLine();
		 input.setText("");
		 helpBuilder.setView(input);
	
		 helpBuilder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  weightPerc = "";
				  weightPerc = input.getText().toString();
				  if (weightPerc.trim().isEmpty()){
					  weightPerc = "100";
				  }
				  addWeightInBD();
				  dialog.cancel();
				  
			  }
		 });
		 helpBuilder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
	}
	
	protected void addTaskWeight() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Select a weight");
		
		int selected = -1; // does not select anything
		taskWeight = "";
		
		builder.setSingleChoiceItems(bdWeights, selected, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				taskWeight =  bdWeights[which];
			}
		});
		
		 builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  if (taskWeight.trim().isEmpty())
					  taskWeight = "Nenhum";
				  dialog.cancel();
				  addTaskInBD();
//				  addSubjectLocal();
			  }
		 });
		 builder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = builder.create();
		 helpDialog.show();
	}
	
	protected void addTaskInBD() {
	    BD bd = new BD();
	    bd.insertTask(this, taskName, date, taskWeight, "normal", 0, "feita", subjectName);
//	    bd.insertSubject(this, subjectName, subjectDescription, subjectTeacher, subjectLocal, semesterName, 0, 1);
	    updateListValues();
	    //	    startActivity(getIntent()); 
//	    finish();
	}   
	
	protected void addWeightInBD() {
	    BD bd = new BD();
	    
	    bd.insertWeight(this, weightName, Float.valueOf(weightPerc), subjectName);
//	    bd.insertTask(this, taskName, date, taskWeight, "normal", 0, "feita", subjectName);
//	    bd.insertSubject(this, subjectName, subjectDescription, subjectTeacher, subjectLocal, semesterName, 0, 1);
	    updateWeights();
	    updateListValues();
	    //	    startActivity(getIntent()); 
//	    finish();
	}   
	
	private void updateWeights(){
		BD bd = new BD();
	    ArrayList<String> tarefas = bd.getWeightBySubject(this, subjectName);
		String[][] tasksAux = new String[tarefas.size()][3];
	    
		bdWeights = new String[tasksAux.length];
	    for (int i = 0; i < tarefas.size(); i++) {
			String[] date = tarefas.get(i).split(" ");
			bdWeights[i] = date[0];
			
		}
	}
	

	private void updateListValues() {
	    ListView subjects = (ListView)findViewById(R.id.listViewTasks);

	    
	    BD bd = new BD();
//	    ArrayList<String> subjectsList = bd.getSubjects(this);

	    ArrayList<String> tasksList = bd.getTaskBySubject(this, subjectName);
		aboutTasks = new String[tasksList.size()][5];
		
	    for (int i = 0; i < tasksList.size(); i++) {
			String[] date = tasksList.get(i).split(" ");
			aboutTasks[i][0] = date[0];
			aboutTasks[i][1] = date[1];
			aboutTasks[i][2] = date[2];
//			aboutSubjects[i][3] = date[3];
//			aboutSubjects[i][4] = date[4];
		}
	    
	    
	    String[] values = new String[aboutTasks.length];
	    for (int i = 0; i < values.length; i++) {
	    	String grade = ""; 
	    	if (Float.valueOf(aboutTasks[i][2]) > 0){
	    		grade = "      " + aboutTasks[i][2] ;
	    	}
			values[i] = aboutTasks[i][0] + grade;
		}
	    
	    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, values);
        
        subjects.setAdapter(adapter);
        subjects.invalidate();
        
	    ListView classes = (ListView)findViewById(R.id.ListViewClasses);

        ArrayList<String> classesList = bd.getClassesBySubject(this, subjectName);
        aboutClasses = new String[classesList.size()][5];
        
        for (int i = 0; i < classesList.size(); i++) {
            String[] date = classesList.get(i).split(" ");
            aboutClasses[i][0] = date[0];
            aboutClasses[i][1] = date[1];
            aboutClasses[i][2] = date[2];
            aboutClasses[i][3] = date[3];
//          aboutSubjects[i][4] = date[4];
        }
        
        
        String[] values2 = new String[aboutClasses.length];
        for (int i = 0; i < values2.length; i++) {
            values2[i] =  aboutClasses[i][1] + " - " + aboutClasses[i][2];
        }
        
	  
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, values2);
	    classes.setAdapter(adapter2);
	    classes.invalidate();
	    
	}
	
    private void addClass() {
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int month = calendar.get(Calendar.MONTH);
        int year = calendar.get(Calendar.YEAR);
        
        Intent intent = new Intent(SubjectsView.this,AddClassView.class);
        intent.putExtra("date", year+"-"+month+"-"+day);
        
        intent.putExtra("subjectName", subjectName);
        intent.putExtra("subjectTeacher", subjectTeacher);
        intent.putExtra("subjectPlace", subjectPlace);
        intent.putExtra("initialDate", intent.getStringExtra("initialDate"));
        intent.putExtra("endDate", intent.getStringExtra("endDate"));
        intent.putExtra("subjectCredits", String.valueOf(subjectCredits));
        intent.putExtra("semesterName", getIntent().getStringExtra("semesterName"));
        intent.putExtra("initialDate", getIntent().getStringExtra("initialDate"));
        intent.putExtra("endDate", getIntent().getStringExtra("endDate"));
        
        SubjectsView.this.startActivity(intent);
        SubjectsView.this.finish();
    }
    
	@Override
	public void onBackPressed() {		
        back();	        		 
        return;
	}

    private void editClass(String id, String initialTime, String endTime, String repetitions) {
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int month = calendar.get(Calendar.MONTH);
        int year = calendar.get(Calendar.YEAR);
        
        Intent intent = new Intent(SubjectsView.this,EditClassView.class);
        intent.putExtra("date", year+"-"+month+"-"+day);
        intent.putExtra("subjectName", subjectName);
        intent.putExtra("subjectTeacher", subjectTeacher);
        intent.putExtra("subjectPlace", subjectPlace);
        intent.putExtra("initialDate", intent.getStringExtra("initialDate"));
        intent.putExtra("endDate", intent.getStringExtra("endDate"));
        intent.putExtra("subjectCredits", String.valueOf(subjectCredits));
        intent.putExtra("semesterName", getIntent().getStringExtra("semesterName"));
        intent.putExtra("initialDate", getIntent().getStringExtra("initialDate"));
        intent.putExtra("endDate", getIntent().getStringExtra("endDate"));
        
        intent.putExtra("id", id);
        intent.putExtra("initialTime", initialTime);
        intent.putExtra("endTime", endTime);
        intent.putExtra("repetitions", repetitions);
     
        SubjectsView.this.startActivity(intent);
        SubjectsView.this.finish();

    }
	private void back() {
		Calendar date = Calendar.getInstance();
		int month = date.get(Calendar.MONTH);
        int year = date.get(Calendar.YEAR);
        int today = date.get(Calendar.DAY_OF_MONTH);
        
	    Intent trocatela = new Intent(SubjectsView.this, SingleSemesterView.class);
		trocatela.putExtra("date", year+"-"+month+"-"+today);

		trocatela.putExtra("semesterName", getIntent().getStringExtra("semesterName"));
		trocatela.putExtra("initialDate", getIntent().getStringExtra("initialDate"));
		trocatela.putExtra("endDate", getIntent().getStringExtra("endDate"));
		trocatela.putExtra("mean", getIntent().getStringExtra("mean"));
		SubjectsView.this.startActivity(trocatela);
		SubjectsView.this.finish();
	}

    private void addTask() {
        addTaskName();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
     super.onCreateOptionsMenu(menu);
     menu.add(0,0,0,"Add class");
     menu.add(0,1,0,"Add task");
     menu.add(1,2,1,"View grade");
     return true;
    } 
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
         super.onOptionsItemSelected(item);
         switch (item.getItemId()) {
            case 0:
                addClass();
                break;
            case 1:
                addTask();
                break;
            case 2:
                seeGrades();
                break;
                
         }
         return false;
    } 
}
